package com.wzf.utils;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;

public class Request2JsonUtils {



	public static String requestToJsonObject(HttpServletRequest request) throws IOException {

        String requestJsonString = getRequestJsonString(request);
        return requestJsonString;
	}
	 /***
     * 获取 request 中 json 字符串的内容
     * 
     * @param request
     * @return : <code>byte[]</code>
     * @throws IOException
     */
    public static String getRequestJsonString(HttpServletRequest request)
            throws IOException {
        String submitMehtod = request.getMethod();
        // GET
        if (submitMehtod.equals("GET")) {
        	if(StringUtils.isNotEmpty(request.getQueryString())){
        		return new String(request.getQueryString().getBytes("iso-8859-1"),"utf-8").replaceAll("%22", "\"");
        	}else{
        		return new String("".getBytes("iso-8859-1"), "utf-8").replaceAll("%22", "\"");
        	}
        // POST
        } else {
            return getRequestPostStr(request);
        }
    }
 
    /**      
     * 描述:获取 post 请求的 byte[] 数组
     * <pre>
     * 举例：
     * </pre>
     * @param request
     * @return
     * @throws IOException      
     */
    public static byte[] getRequestPostBytes(HttpServletRequest request)
            throws IOException {
        BufferedReader reader = request.getReader();
        StringBuilder sb =new StringBuilder("");
        String str;
        while ((str =reader.readLine())!=null){
            sb.append(str);
        }
        return sb.toString().getBytes();
    }
 
    /**      
     * 描述:获取 post 请求内容
     * <pre>
     * 举例：
     * </pre>
     * @param request
     * @return
     * @throws IOException      
     */
    public static String getRequestPostStr(HttpServletRequest request)
            throws IOException {
        byte buffer[] = getRequestPostBytes(request);
        String charEncoding = request.getCharacterEncoding();
        if (charEncoding == null) {
            charEncoding = "UTF-8";
        }
        return new String(buffer, charEncoding);
    }
}